<template>
	<MainPage>
		<template v-slot:HeaderLeft>
			<el-form
				:inline="true"
				:model="form"
				class="demo-form-inline"
				ref="userListFrom"
				label-width="70px"
			>
				<el-form-item label="工艺名称" prop="name">
					<el-input
						v-model="form.name"
						placeholder="工艺名称"
						class="wid220"
					></el-input>
				</el-form-item>
				<el-form-item label="成品" prop="goods_spu_id">
					<change-goods-input
						ref="changeGoodsInput"
						@clear="
							() => {
								form.goods_spu_id = '';
							}
						"
						@sendValue="
							(data) => {
								form.goods_spu_id = data.id;
							}
						"
					></change-goods-input>
				</el-form-item>

				<el-form-item label="创建时间" prop="create_time">
					<el-date-picker
						v-model="create_time"
						type="daterange"
						class="time220"
						:editable="false"
						unlink-panels
						range-separator="至"
						start-placeholder="开始日期"
						end-placeholder="结束日期"
						value-format="yyyy-MM-dd"
						:clearable="false"
						@change="getArticleList"
					/>
				</el-form-item>

				<!-- <div class="clearfix"></div> class="marginTop10"-->
				<el-form-item>
					<el-button class="reset marginLeft10" type="primary" @click="reset"
						>重置</el-button
					>
					<el-button
						type="primary"
						@click="getArticleList"
						:loading="listLoading"
						>搜索</el-button
					>
				</el-form-item>
			</el-form>
		</template>
		<template v-slot:HeaderRight
			><el-button @click="(dialogTitle = '新增工艺'), (addCraftDialog = true)">
				新增工艺</el-button
			>
		</template>
		<template v-slot:Table>
			<div style="min-height: 200px">
				<el-table
					ref="multipleTable"
					v-loading="listLoading"
					:data="list"
					element-loading-text="加载中"
					fit
					border
					highlight-current-row
				>
					<el-table-column label="工艺名称" prop="name" width="240" />
					<el-table-column prop="order_list" width="240">
						<template #header>
							<span>成品</span
							><el-tooltip class="item" effect="dark" placement="top">
								<div slot="content">注释：成品不再参与【计划采购】计算</div>
								<i class="el-icon-question icon"></i>
							</el-tooltip>
						</template>
						<template slot-scope="scope">
							{{ scope.row.goods_name }}
						</template>
					</el-table-column>
					<el-table-column
						label="工艺说明"
						show-overflow-tooltip
						prop="remark"
						min-width="240"
					/>
					<el-table-column label="创建时间" width="240">
						<template slot-scope="scope">
							{{ parseTime(scope.row.created_at) }}
						</template>
					</el-table-column>
					<el-table-column
						label="操作"
						width="160"
						fixed="right"
						align="center"
						prop="order_list"
					>
						<template slot-scope="scope">
							<el-link type="success" v-repeatClick @click="handleEdit(scope)">
								编辑</el-link
							>
							<el-link
								type="warning"
								v-repeatClick
								@click="handleDelete(scope)"
							>
								删除</el-link
							>
						</template></el-table-column
					>
				</el-table>
			</div>
		</template>
		<template v-slot:Page>
			<el-pagination
				:current-page="current.page"
				:page-sizes="[20, 50, 100]"
				:page-size="limit"
				layout="total, sizes, prev, pager, next, jumper"
				:total="totalCount"
				background
				@size-change="changeLimit"
				@current-change="changePage"
			/>
		</template>
		<template v-slot:Dialog>
			<el-dialog
				:title="dialogTitle"
				:visible.sync="addCraftDialog"
				class="main_dialog dialog800"
				@closed="closeCraftDialog"
			>
				<el-form
					:inline="false"
					:model="craftInfo"
					:rules="rules"
					class="demo-form-inline"
					ref="craftInfoRef"
					label-width="80px"
					key="userListFrom1"
				>
					<div>
						<el-form-item label="工艺名称" :rules="rules.name" prop="form.name">
							<el-input
								v-model="craftInfo.form.name"
								placeholder="工艺名称"
								class="wid220"
							></el-input>
						</el-form-item>
						<el-form-item
							label="成品"
							:rules="rules.goods_spu_id"
							prop="form.goods_spu_id"
						>
							<change-goods-input
								ref="changeGoodsInput1"
								url="1"
								@clear="clearGoodsInput(1)"
								@sendValue="(data) => getGoodsInputData(data, 1)"
							></change-goods-input>
						</el-form-item>
						<el-form-item
							label="工艺说明"
							:rules="rules.remark"
							prop="form.remark"
						>
							<el-input
								v-model="craftInfo.form.remark"
								type="textarea"
								:rows="2"
								placeholder="工艺说明"
								class="textarea"
							></el-input>
						</el-form-item>
						<div class="add_goods_container">
							<li>
								<span> <em>*</em>商品 </span>
								<change-goods-input
									ref="changeGoodsInput2"
									url="1"
									@clear="clearGoodsInput(2)"
									@sendValue="(data) => getGoodsInputData(data, 2)"
								></change-goods-input>
							</li>
							<li>
								<span class="width60"> <em>*</em>数量 </span>
								<el-input
									v-model="craftInfo.add_form.num"
									ref="addGoodsNum"
									class="add_form_numinput"
									@keyup.enter.native="addGoodsList"
								></el-input>
							</li>
							<li>
								<el-button type="primary" @click="addGoodsList">添加</el-button>
							</li>
						</div>
						<div class="main_table table_container" style="min-height: 200px">
							<el-table
								ref="multipleTable"
								v-loading="listLoading"
								:data="craftInfo.list"
								element-loading-text="加载中"
								fit
								border
								highlight-current-row
							>
								<el-table-column label="序号" width="60">
									<template slot-scope="scope">
										{{ scope.$index + 1 }}
									</template>
								</el-table-column>
								<el-table-column label="原料名称" prop="name" />
								<el-table-column label="单位" prop="spu_unit" />
								<el-table-column label="数量" prop="num">
									<template slot-scope="scope">
										<el-input-number
											v-model="scope.row.num"
											:controls="false"
											:min="0"
											:precision="2"
											:class="'num_list' + scope.$index"
										></el-input-number>
									</template>
								</el-table-column>
								<el-table-column
									label="操作"
									fixed="right"
									align="center"
									prop="order_list"
								>
									<template slot-scope="scope">
										<el-link type="warning" @click="CraftDelete(scope)">
											删除</el-link
										>
									</template></el-table-column
								>
							</el-table>
						</div>
					</div>
				</el-form>
				<div slot="footer" class="dialog-footer">
					<el-button
						type="primary"
						:loading="saveloading"
						@click="preserve"
						v-repeatClick
						>保存</el-button
					>
					<el-button @click="addCraftDialog = false">取消</el-button>
				</div>
			</el-dialog>
		</template>
	</MainPage>
</template>
<script>
	import MainPage from "@/components/MainPage";
	import {
		recursion,
		category,
		parseTime,
		getyesterday,
		jsonStringifyBack,
	} from "@/utils/index";
	import rules from "@/rules/sorting/processCraft";
	import {
		formula_index,
		formula_info,
		formula_add,
		formula_edit,
		formula_delete,
	} from "@/api/sorting/processCraft";
	let add_form = {
		num: "",
		name: "",
		goods_spu_id: "",
		goods_id: "",
		spu_unit: "",
	};
	export default {
		components: {
			MainPage,
		},

		data() {
			return {
				parseTime,
				rules,
				form: {
					name: "",
					start_time: "",
					end_time: "",
					goods_spu_id: "",
					// create_time: parseTime(new Date(), "{y}-{m}-{d}"),
				},
				create_time: [],
				listLoading: false,
				list: [],
				// 分页
				current: {
					page: 1,
					per_page: 20,
				},
				limit: 20,
				totalCount: 1,
				//  新增工艺
				dialogTitle: "新增工艺",
				addCraftDialog: false,
				saveloading: false,
				craftInfo: {
					form: {
						name: "",
						goods_spu_id: "",
						goods_id: "",
						remark: "",
					},
					add_form: {
						num: "",
						name: "",
						goods_spu_id: "",
						goods_id: "",
						spu_unit: "",
					},
					list: [],
				},
				// 编辑工艺
				editId: "",
				delete_ids: [],
			};
		},
		methods: {
			// 搜索
			getArticleList() {
				this.current.page = 1;
				this.formula_index();
			},
			//重置
			reset() {
				if (this.$refs["changeGoodsInput"]) {
					this.$refs["changeGoodsInput"].name = "";
				}
				this.create_time = [];
				this.getArticleList();
			},
			// 分页
			changeLimit(pageSize) {
				this.current.per_page = pageSize;
				this.formula_index();
			},
			changePage(page) {
				this.current.page = page;
				this.formula_index();
			},
			// 编辑
			handleEdit(scope) {
				this.dialogTitle = "编辑工艺";
				let data = { id: scope.row.id };
				this.editId = scope.row.id;
				formula_info(data).then((res) => {
					if (res.errcode == 0) {
						let response = res.data.info;
						this.craftInfo.form.name = response.name;
						this.craftInfo.form.remark = response.remark;
						this.craftInfo.form.goods_spu_id = response.goods_spu_id;
						this.craftInfo.form.goods_id = response.goods_id;
						let list = [];
						response.formula_list.map((e) => {
							list.push({
								num: Number(e.num),
								name: `${e.goods.name}【${e.spu.spu_name.title}】`,
								goods_spu_id: e.goods_spu_id,
								goods_id: e.goods_id,
								spu_unit: e.spu.spu_unit.title,
								id: e.id,
							});
						});
						this.craftInfo.list = list;
						this.addCraftDialog = true;
						this.$nextTick(() => {
							if (this.$refs["changeGoodsInput1"]) {
								let goods_name = response.goods.name;
								try {
									goods_name = `${goods_name}【${response.spu.spu_name.title}】`;
								} catch (error) {
									console.error(error);
								}
								this.$refs["changeGoodsInput1"].name = goods_name;
							}
						});
					} else {
						this.$message.error(res.errmsg);
					}
				});
			},
			// 删除
			handleDelete(scope) {
				let id = scope.row.id;
				let message = `此操作将删除当前工艺【${scope.row.name}】, 是否继续?`;
				this.$confirm(message, "提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning",
				})
					.then(() => {
						let data = {
							id: id,
						};
						formula_delete(data).then((res) => {
							if (res.errcode == 0) {
								this.$message.success("删除成功");
								this.formula_list();
							}
						});
					})
					.catch(() => {});
			},

			// 列表
			formula_index() {
				this.form.start_time = this.create_time ? this.create_time[0] : "";
				this.form.end_time = this.create_time ? this.create_time[1] : "";
				let data = Object.assign(this.current, this.form);
				this.listLoading = true;
				formula_index(data).then((res) => {
					if (res.errcode == 0) {
						this.totalCount = res.data.list.total;
						res.data.list.data.map((e) => {
							e.goods_name = e.goods.name;
							try {
								e.goods_name = `${e.goods_name}【${e.spu.spu_name.title}】`;
							} catch (error) {
								console.error(error);
							}
						});
						this.list = res.data.list.data;
						this.listLoading = false;
					} else {
						this.$message.error(res.errmsg);
					}
				});
			},
			// 商品选择框清除
			clearGoodsInput(type) {
				switch (type) {
					case 1:
						this.craftInfo.form.goods_spu_id = "";
						this.craftInfo.form.goods_id = "";
						break;
					case 2:
						break;
				}
			},
			// 商品选择框选择
			getGoodsInputData(data, type) {
				// console.log(data);
				switch (type) {
					case 1:
						this.craftInfo.form.goods_id = data.goods_id;
						this.craftInfo.form.goods_spu_id = data.id;
						this.$nextTick(() => {
							this.$refs["craftInfoRef"].clearValidate("goods_spu_id");
						});
						break;
					case 2:
						this.craftInfo.add_form.goods_id = data.goods_id;
						this.craftInfo.add_form.goods_spu_id = data.id;
						this.craftInfo.add_form.spu_unit = data.spu_unit.title;
						let spu_title = data.spu_name ? data.spu_name.title : "";
						this.craftInfo.add_form.name = `${data.goods.name}【${spu_title}】`;
						this.$nextTick(() => {
							this.$refs["addGoodsNum"].focus();
						});
						break;
				}
			},
			// 列表添加选择商品
			addGoodsList() {
				let num = this.craftInfo.add_form.num;
				let goods_spu_id = this.craftInfo.add_form.goods_spu_id;
				if (num !== null && num !== undefined && num !== "" && goods_spu_id) {
					let form = JSON.parse(JSON.stringify(this.craftInfo.add_form));
					let find_data_index = this.craftInfo.list.findIndex((e, index) => {
						return e.goods_spu_id == goods_spu_id;
					});
					if (find_data_index === -1) {
						this.craftInfo.list.push(form);
					} else {
						this.$nextTick(() => {
							let classname = `.num_list${find_data_index}`;
							let input = document.querySelector(`${classname} .el-input  input`);
							input.focus();
						});
					}
					this.addGoodsReset();
				}
			},
			// 添加重置
			addGoodsReset() {
				this.craftInfo.add_form = JSON.parse(JSON.stringify(add_form));
				this.$refs["changeGoodsInput2"].name = "";
				this.$refs["changeGoodsInput2"].focus();
			},
			// 删除工艺商品
			CraftDelete(scope) {
				let index = scope.$index;
				this.delete_ids.push(scope.row.id);
				this.craftInfo.list.splice(index, 1);
			},
			// 保存工艺
			preserve() {
				this.$refs["craftInfoRef"].validate((valid) => {
					if (valid) {
						if (this.craftInfo.list.length == 0) {
							this.$message.error("请添加原料");
							return;
						}
						this.saveloading = true;
						let form = this.craftInfo.form;
						let listArray = this.craftInfo.list.map((e) => {
							let { name, spu_unit, ...sz } = e;
							return { ...sz };
						});
						form.list = JSON.stringify(listArray, jsonStringifyBack);

						if (this.dialogTitle == "新增工艺") {
							this.$confirm(
								"工艺新增成功后，成品不再参与【计划采购】计算，确定吗？",
								"提示",
								{
									confirmButtonText: "确定",
									cancelButtonText: "取消",
									type: "warning",
								}
							)
								.then(() => {
									this.formula_add(form);
								})
								.catch(() => {});
						} else {
							this.formula_edit(form);
						}
					}
				});
			},
			// 新增工艺保存
			formula_add(form) {
				formula_add(form).then((res) => {
					if (res.errcode == 0) {
						this.$message.success("添加成功");
						this.addCraftDialog = false;
						this.formula_index();
					} else {
						this.$message.error(res.errmsg);
					}
					this.saveloading = false;
				});
			},
			// 编辑工艺保存
			formula_edit(form) {
				let edit_form = {
					id: this.editId,
					delete_ids: this.delete_ids.join(","),
				};
				let data = Object.assign(edit_form, form);
				formula_edit(data).then((res) => {
					if (res.errcode == 0) {
						this.$message.success("编辑成功");
						this.addCraftDialog = false;
						this.formula_index();
					} else {
						this.$message.error(res.errmsg);
					}
					this.saveloading = false;
				});
			},
			// 新增工艺关闭回调
			closeCraftDialog() {
				if (this.$refs["changeGoodsInput1"]) {
					this.$refs["changeGoodsInput1"].name = "";
				}
				this.craftInfo.form = {
					name: "",
					goods_spu_id: "",
					goods_id: "",
					remark: "",
				};
				this.craftInfo.add_form = {
					num: "",
					name: "",
					goods_spu_id: "",
					goods_id: "",
					spu_unit: "",
				};
				this.craftInfo.list = [];
				this.delete_ids = [];
			},
		},
		created() {
			this.formula_index();
		},
	};
</script>
<style lang='scss' scoped>
.textarea {
	width: 280px;
	>>> .el-textarea__inner {
		height: auto;
	}
}
.add_goods_container {
	display: flex;
	align-items: center;
	padding: 0 0 0 0px;
	li {
		display: flex;
		align-items: center;
		span {
			padding-right: 10px;
			display: block;
			width: 80px;
			text-align: right;
			em {
				padding: 0 5px;
				color: red;
			}
		}
		.width60 {
			width: 60px;
		}
		&:last-child {
			margin-left: 10px;
		}
	}
}
>>> .table_container .el-table--small td .cell {
	height: auto;
}
.icon {
	margin-left: 5px;
	vertical-align: baseline;
}
/deep/ .el-input-number .el-input__inner {
	text-align: left;
}
</style>
